<template>
  <div class="coupon-list">
    <!-- 搜索栏 -->
    <el-card class="mb-4">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="车牌号">
          <el-input style="max-width: 300px;" v-model="searchForm.plateNo" placeholder="请输入车牌号" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="exportData" v-has="'carParkOrder:export'">导出</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  
    <!-- 列表 -->
    <el-table :data="tableData" style="width: 100%;margin-top: 15px" border>
      <el-table-column prop="id" label="ID" width="40" />
      <el-table-column prop="userCarId" label="用户车辆ID" />
      <el-table-column prop="plateNo" label="车牌" />
      <el-table-column prop="parkName" label="停车地点" />
      <el-table-column prop="parkDuration" label="停车时长" />
      <el-table-column prop="entryTime" label="入场时间" />
      <el-table-column prop="deductAmount" label="抵扣金额" />
      <el-table-column prop="totalAmount" label="停车费总额" />
      <el-table-column prop="paidCredit" label="支付积分" />
      <el-table-column prop="createTime" label="订单时间" />
      <el-table-column prop="deductHours" label="抵扣时长（小时）">
        <template slot-scope="scope">
          {{scope.row.deductHours}}（小时）
        </template>
      </el-table-column>
      <el-table-column prop="couponSolutionNo" label="优惠方案编号" />
    </el-table>
  
    <!-- 分页 -->
    <div class="pagination">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page.sync="currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="pageSize"
        layout="total, sizes, prev, pager, next" :total="total">
      </el-pagination>
    </div>
  </div>
</template>
  
  <script>
export default {
  name: 'CouponList',
  data() {
    return {
      // 搜索表单
      searchForm: {
        plateNo: ''
      },
      // 表格数据
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      // 弹窗相关
      dialogVisible: false,
      // 表单数据
      form: {
        id: '',
        credit: 0,
        auditStatus: 1,
        reason: ''
      },
      rules: {
        reason: [{ required: true, message: '请输入拒绝原因', trigger: 'blur' }],
      },
    }
  },
  async created() {
    console.log(localStorage.getItem('token'))
    this.getList()

  },
  methods: {
    async exportData() {
      // 显示加载中
      const loading = this.$loading({
        lock: true,
        text: '导出中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });

      try {
        // 准备导出参数
        const params = {
          page: this.currentPage,
          size: this.pageSize,
        };

        // 调用导出API
        const { data } = await this.$api.exportCarParkOrder(params);

        // 创建下载链接
        if (data) {
          // 如果返回的是文件流
          if (data instanceof Blob) {
            const blob = new Blob([data]);
            const url = window.URL.createObjectURL(blob);
            const link = document.createElement('a');
            link.href = url;
            link.download = '停车场订单数据.xlsx'; // 设置下载文件名
            link.click();
            window.URL.revokeObjectURL(url);
            this.$message.success('导出成功');
          }
          // 如果返回的是下载链接
          else if (typeof data === 'string') {
            this.$message.success('导出成功');
            window.open(data, '_blank');
          }
          // 如果返回的是其他格式的数据
          else {
            this.$message.success('导出成功');
            console.log(data, '导出数据');
          }
        } else {
          this.$message.warning('没有可导出的数据');
        }
      } catch (error) {
        console.error('导出失败', error);
        this.$message.error('导出失败：' + (error.message || '未知错误'));
      } finally {
        // 关闭加载中
        loading.close();
      }
    },
    // 获取列表数据
    async getList() {
      try {
        const params = {
          page: this.currentPage,
          size: this.pageSize,
          condition: {
            ...this.searchForm,
          }
        }
        // 这里替换为实际的API调用
        const { data } = await this.$api.getcarParkOrder(params)
        data.result.records.forEach(e => {
          e.createTime = e.createTime ? e.createTime.replace(/T/, ' ') : ''
          e.entryTime = e.entryTime ? e.entryTime.replace(/T/, ' ') : ''
        })
        this.tableData = data.result.records
        this.total = data.result.total
      } catch (error) {
        console.error('获取列表失败：', error)
        this.$message.error('获取列表失败')
      }
    },
    // 审核
    handleEdit(row) {
      this.dialogVisible = true
      this.form.id = row.id
      // this.$confirm('确认审核该小票吗？', '提示', {
      //   type: 'warning'
      // }).then(async () => {
      //   try {
      //     await this.$api.receiptAudit(row.id, {
      //       auditStatus: 1,
      //       credit: row.credit
      //     })
      //     this.$message.success('审核成功')
      //     this.getList()
      //   } catch (error) {
      //     console.error('审核失败：', error)
      //   }
      // }).catch(() => {
      // })
    },
    // 拒绝
    handleEdit1(row) {
      this.$confirm('确认拒绝该小票吗？', '提示', {
        type: 'warning'
      }).then(async () => {
        try {
          await this.$api.receiptAudit(row.id, {
            auditStatus: 2,
            credit: row.credit
          })
          this.$message.success('拒绝成功')
          this.getList()
        } catch (error) {
          console.error('拒绝失败：', error)
        }
      }).catch(() => {
      })
    },

    // 搜索
    handleSearch() {
      this.currentPage = 1
      this.getList()
    },

    // 重置搜索
    resetSearch() {
      this.searchForm.shelf = ''
      this.handleSearch()
    },

    // 修改状态
    async handleStatusChange(value, row) {
      try {
        await this.$api.creditProductStatus(row.id, value)
        this.$message.success('状态修改成功')
      } catch (error) {
        console.error('状态修改失败：', error)
        this.$message.error('状态修改失败')
        row.shelf = !value // 恢复原状态
      }
    },

    // 分页相关
    handleSizeChange(val) {
      this.pageSize = val
      this.getList()
    },

    handleCurrentChange(val) {
      this.currentPage = val
      this.getList()
    },
    // 提交审核
    async submitAudit() {

      this.$refs.formRef.validate(async (valid) => {
        if (valid) {
          try {
            await this.$api.receiptAudit(this.form.id, {
              auditStatus: this.form.auditStatus,
              credit: this.form.credit,
              reason: this.form.reason
            })
            this.$message.success('审核成功')
            this.dialogVisible = false
            this.getList()
          } catch (error) {
            console.error('审核失败：', error)
            this.$message.error('审核失败')
          }
        }
      })
    },
  }
}
  </script>
  
  <style scoped lang="scss">
.flex_flex {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
  }
  
  .w-full {
    width: 100%;
  }
  
  .coupon-list {
    padding: 20px;
  }
  
  
  
  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
  
  .avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  
  .avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }
  
  .avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
  }
  
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
    line-height: 178px;
  }
</style>